import 'dart:developer' as developer;

import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/tools/cn_common_global.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';

import '../../tools/cn_style.dart';
import '../../tools/cn_time.dart';
import '../../tools/cn_widget_util.dart';
// import '../../../../generated/l10n.dart';
import '../../tools/cn_chartRechargeCard_message.dart';
import '../../tools/cn_event_bus.dart';
import 'package:provider/provider.dart';
import 'package:flutter_application_cyber/model/user_info_datesource.dart';
class CnConversationListItem extends StatefulWidget {
  RCIMIWConversation? conversation;
  CnConversationListItemDelegate? delegate;
  UserInfo? info;
  late _CnConversationListItemState state;

  CnConversationListItem(delegate, conversation, {super.key}) {
    this.conversation = conversation;
    this.delegate = delegate;

    setInfo();
  }

  @override
  State<StatefulWidget> createState() {
    return state = new _CnConversationListItemState(delegate, conversation);
  }

  void setInfo() async {
    // if (mounted) setState(() {});
    String? targetId = conversation!.targetId;
    UserInfo? userInfo =
        UserInfoDataSource.cachedUserMap[targetId];
   
    if ( conversation!.conversationType == RCIMIWConversationType.private) {
      if (userInfo != null) {
         info = userInfo;
      }  else {
        UserInfo userInfo =
            await UserInfoDataSource.getUserInfo(targetId);
        if (userInfo.id != null) {
         info = userInfo; 

      } else{

         CnNetHelper.getTargetUserInfo(targetId!,
            (UserInfoModel model, bool result, String msg) {
          if (result) { 
               UserInfo? userInfo =
        UserInfoDataSource.cachedUserMap[targetId];
            info = userInfo;
            // if(this.state !=null ){
            //   this.state.setState(() {
                
            //   });
            // }
          //  CnEventBus.instance!.commit(EventKeys.ConversationPageDispose, null);

          } });   

      }
           
      }

      
      
    } 
  }
  
}

class _CnConversationListItemState extends State<CnConversationListItem> {
  String pageName = "example.CnConversationListItem";
  CnConversationListItemDelegate? delegate;
  Offset? tapPos;
  String lastMessageText = '';
  String  avatarUrl = '';
  // UserInfoModel getUserInfo() {
  //   return Provider.of<ChangeUserInfoModel>(context, listen: true).info;
  // }

  _CnConversationListItemState(
      CnConversationListItemDelegate? delegate, RCIMIWConversation? con) {
    this.delegate = delegate;
  }

  void _refreshUI() {
    setState(() {});
  }

  void _onTaped() {
    if (this.delegate != null) {
      this.delegate!.didTapConversation(widget.conversation);
    } else {
      developer.log("没有实现 CnConversationListItemDelegate", name: pageName);
    }
  }

  void _onLongPressed() {
    if (this.delegate != null) {
      this.delegate!.didLongPressConversation(widget.conversation, this.tapPos);
    } else {
      developer.log("没有实现 CnConversationListItemDelegate", name: pageName);
    }
  }

  Widget _buildPortrait() {
    return Stack(
      children: <Widget>[
        Row(
          children: <Widget>[
            SizedBox(
              width: 8,
            ),
            CnWidgetUtil.buildUserPortrait(widget.info?.portraitUrl),

          ],
        ),
      ],
    );
  }

  Widget _buildContent() {
    return Expanded(
      child: Container(
          height: RCLayout.ConListItemHeight,
          margin: EdgeInsets.only(left: 8),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 28,
                margin: EdgeInsets.only(top: 5, bottom: 5),
                child: Row(
                  children: <Widget>[_buildTitle(), _buildTime()],
                ),
              ),
              Row(
                children: <Widget>[
                  _buildLastMessageText(),
                  Container(
                      margin: EdgeInsets.only(bottom: 0, right: 20),
                      child:
                          _buildUnreadCount(widget.conversation!.unreadCount!))
                ],
              ),
            ],
          )),
    );
  }

  Widget _buildTime() {
    String time = TimeUtil.convertShortTextTime(
        widget.conversation!.lastMessage!.receivedTime!);
    List<Widget> _rightArea = <Widget>[
      Text(
        time,
        style: TextStyle(
            fontSize: RCFont.ConListTimeFont,
            color: Color(RCColor.ConListTimeColor)),
      ),
      // SizedBox(
      //   height: 15,
      // )
    ];
    return Container(
      width: RCLayout.ConListItemHeight,
      margin: EdgeInsets.only(right: 8),
      child: Column(
          mainAxisAlignment: MainAxisAlignment.center, children: _rightArea),
    );
  }

  Widget _buildTitle() {
    String title = (widget.conversation!.conversationType ==
            RCIMIWConversationType.private
        ? (widget.info == null || widget.info!.name == null ? "" : widget.info!.name!)
        : "");
        //+ (this.info == null || this.info!.id == null ? "" : this.info!.id!);
    String? digest = "";
    if (digest == null) {
      digest = "";
    }
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            constraints: BoxConstraints(
              maxWidth: 300,
              maxHeight: 30,
            ),
            child: Text(
              title,
              style: const TextStyle(
                  fontSize: RCFont.ConListTitleFont,
                  color: Color(RCColor.ConListTitleColor),
                  fontWeight: FontWeight.w700),
              maxLines: 1,
              // overflow: TextOverflow.ellipsis,
            ),
          )

          // SizedBox(
          //   height: 6,
          // ),
          // _buildDigest(digest)
        ],
      ),
    );
  }

  Widget _buildLastMessageText() {
    if (widget.conversation!.lastMessage != null) {
      RCIMIWMessage lastMessage = widget.conversation!.lastMessage!;

      if (lastMessage is RCIMIWTextMessage) {
        RCIMIWTextMessage textMessage = lastMessage as RCIMIWTextMessage;
        lastMessageText = textMessage.text!;
      } else if (lastMessage is RCIMIWImageMessage) {
        lastMessageText = '[Image]';
      } else if (lastMessage is RCIMIWVoiceMessage) {
        lastMessageText = '[Voice]';
      }
      // else if (lastMessage is RCIMIWCustomMessage) {
      //   lastMessageText = S.of(context).text_gift;
      // }
      else if (lastMessage is CnRCIMDChartRechargeCardMessage) {
        //充值卡片消息
        CnRCIMDChartRechargeCardMessage customMessage =
            lastMessage as CnRCIMDChartRechargeCardMessage;
        if (customMessage.pokeMessage!.contains("tpp")) {
          lastMessageText = '[Recharge]';
        }
      }
    } else {
      IRCIMIWGetMessagesCallback? callback =
          IRCIMIWGetMessagesCallback(onSuccess: (List<RCIMIWMessage>? t) {
//...
        if (t != null) {
          widget.conversation!.lastMessage = t.last;

          RCIMIWMessage lastMessage = widget.conversation!.lastMessage!;

          if (lastMessage is RCIMIWTextMessage) {
            RCIMIWTextMessage textMessage = lastMessage as RCIMIWTextMessage;
            lastMessageText = textMessage.text!;
          } else if (lastMessage is RCIMIWImageMessage) {
            lastMessageText = '[Image]';
          } else if (lastMessage is RCIMIWVoiceMessage) {
            lastMessageText = '[Voice]';
          }
          // else if (lastMessage is RCIMIWCustomMessage) {
          //   lastMessageText = S.of(context).text_gift;
          // }
          else if (lastMessage is CnRCIMDChartRechargeCardMessage) {
            //充值卡片消息
            CnRCIMDChartRechargeCardMessage customMessage =
                lastMessage as CnRCIMDChartRechargeCardMessage;
            if (customMessage.pokeMessage!.contains("tpp")) {
              lastMessageText = '[Recharge]';
            }
          }
          setState(() {});
        }
      }, onError: (int? code) {
//...
        print(code);
      });

      DateTime now = DateTime.now();
      int sentTime = now.millisecondsSinceEpoch;
      CnGlobal.engine!.getMessages(
          RCIMIWConversationType.private!,
          widget.conversation!.targetId!,
          null,
          sentTime,
          RCIMIWTimeOrder.before,
          RCIMIWMessageOperationPolicy.local,
          1,
          callback: callback); //最后一条message
    }

    return Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          // SizedBox(
          //   height: 6,
          // ),
          _buildDigest(lastMessageText),
          // SizedBox(
          //   height: 6,
          // ),
          // (conversation!.lastMessage is RCIMIWImageMessage)||(conversation!.lastMessage is RCIMIWVoiceMessage)? Container():Text(
          //    (conversation!.draft != null && conversation!.draft!.isNotEmpty)?'':lastMessageText,
          //   style: TextStyle(fontSize: RCFont.ConListLastMessageTextFont, color: Color(RCColor.ConListLastMessageTextColor), fontWeight: FontWeight.w400),
          //   maxLines: 1,
          //   overflow: TextOverflow.ellipsis,
          // ),
        ],
      ),
    );
  }

  Widget _buildDigest(String digest) {
    bool showError = false;
    if (widget.conversation!.mentionedCount! > 0) {
      digest = RCString.ConHaveMentioned + digest;
    } else if (widget.conversation!.draft != null &&
        widget.conversation!.draft!.isNotEmpty) {
      digest = RCString.ConDraft + widget.conversation!.draft!;
    } else if (widget.conversation!.lastMessage?.sentStatus ==
        RCIMIWSentStatus.failed) {
      showError = true;
    }
    double screenWidth = MediaQuery.of(context).size.width;
    if (showError) {
      return Row(children: <Widget>[
        // conversation.sentStatus == RCSentStatus.Failed ?
        Icon(
          Icons.error,
          size: 15,
          color: Colors.red,
        ),
        Container(
            width: screenWidth - 150,
            child: Text(
              digest,
              style: TextStyle(
                  fontSize: RCFont.ConListDigestFont,
                  color: Color(RCColor.ConListDigestColor)),
              maxLines: 1,
              overflow: TextOverflow.visible,
            ))
      ]);
    } else if (widget.conversation!.draft != null &&
        widget.conversation!.draft!.isNotEmpty) {
      return RichText(
        text: TextSpan(
            style: TextStyle(fontSize: RCFont.ConListDigestFont),
            children: [
              TextSpan(
                  text: RCString.ConDraft, style: TextStyle(color: Colors.red)),
              TextSpan(
                  text: widget.conversation!.draft,
                  style: TextStyle(color: Color(RCColor.ConListDigestColor))),
            ]),
        textDirection: TextDirection.ltr,
      );
    } else {
      return Container(
          width: screenWidth - 150,
          child: Text(
            digest,
            style: TextStyle(
                fontSize: RCFont.ConListDigestFont,
                color: Color(RCColor.ConListDigestColor)),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ));
    }
  }

  Widget _buildUnreadCount(int count) {
    if (count <= 0 || count == null) {
      return CnWidgetUtil.buildEmptyWidget();
    }
    double width = count > 100 ? 35 : 25;
    return Container(
        width: width,
        height: RCLayout.ConListUnreadSize,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(width / 2.0),
            color: Color(RCColor.ConListUnreadColor)),
        child: Text(count > 99 ? '99+' : '+' + count.toString(),
            style: TextStyle(
                fontSize: RCFont.ConListUnreadFont,
                color: Color(RCColor.ConListUnreadTextColor))));
  }

  @override
  void initState() {
    super.initState();
    // if (mounted) {//首次打开为空
      setInfo(); 
    // } 
  }
   void setInfo() async {
    // if (mounted) setState(() {});
    String? targetId = widget.conversation!.targetId;
    UserInfo? userInfo =
        UserInfoDataSource.cachedUserMap[targetId];
   
    if ( widget.conversation!.conversationType == RCIMIWConversationType.private) {
      if (userInfo != null) {
        widget.info = userInfo;
         setState(() {});
      }  else {
        UserInfo userInfo =
            await UserInfoDataSource.getUserInfo(targetId);
        if (userInfo.id != null) {
        widget.info = userInfo;
        setState(() {});
      }else{ 

         CnNetHelper.getTargetUserInfo(targetId!,
            (UserInfoModel model, bool result, String msg) {
          if (result) { 
               UserInfo? userInfo =
        UserInfoDataSource.cachedUserMap[targetId];
             widget.info = userInfo;
             setState(() {});
          } });   
      }   
      }
    } 
   }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
          onTapDown: (TapDownDetails details) {
            tapPos = details.globalPosition;
          },
          onTap: () {
            _onTaped();
          },
          onLongPress: () {
            _onLongPressed();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
            color: Colors.white,
            height: 75,
            width: double.infinity,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[_buildPortrait(), _buildContent()],
            ),
          )),
    );
  }
}

abstract class CnConversationListItemDelegate {
  ///点击了会话 item
  void didTapConversation(RCIMIWConversation? conversation);

  ///长按了会话 item
  void didLongPressConversation(
      RCIMIWConversation? conversation, Offset? tapPos);
}
